<?php

/**
 * This is the model class for table "tbl_invoice_ledger".
 *
 * The followings are the available columns in table 'tbl_invoice_ledger':
 * @property integer $id
 * @property string $invoice
 * @property string $counter
 * @property string $partno
 * @property integer $firstline
 * @property string $description
 * @property string $qty
 * @property string $price
 * @property string $warehouse
 * @property string $ptype
 * @property string $jbclass
 * @property string $serial
 * @property string $sdebit
 * @property string $scredit
 * @property string $cost
 * @property string $cdebit
 * @property string $ccredit
 * @property string $tax1
 * @property string $tax2
 * @property string $tax3
 * @property string $tax4
 * @property string $tax5
 * @property string $tax6
 * @property string $epa
 * @property string $miscnum
 * @property string $warranty
 * @property string $refrlbs
 * @property integer $noprint
 * @property integer $taxed
 * @property integer $costed
 * @property string $eqcounter
 * @property string $entryid
 * @property string $assemblyid
 * @property string $assemblyqty
 * @property string $markupvalue
 */
class InvoiceLedger extends CActiveRecord {

    public $old_qty;

 

    /**
     * Returns the static model of the specified AR class.
     * @return InvoiceLedger the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    const TAXED = 0;
    const NO_TAXED = -1;

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'tbl_invoice_ledger';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            //array('invoice, counter, partno, firstline, description, qty, price, warehouse, ptype, jbclass, serial, sdebit, scredit, cost, cdebit, ccredit, tax1, tax2, tax3, tax4, tax5, tax6, epa, miscnum, refrlbs, noprint, taxed, costed, eqcounter, entryid, assemblyid, assemblyqty, markupvalue', 'required'),
            array('firstline, noprint, taxed, costed', 'numerical', 'integerOnly' => true),
            array('invoice, qty, price, sdebit, scredit, cost, cdebit, ccredit, tax1, tax2, tax3, tax4, tax5, tax6, epa, miscnum, refrlbs, assemblyqty, markupvalue', 'length', 'max' => 10),
            array('counter', 'length', 'max' => 3),
            array('partno', 'length', 'max' => 50),
            array('warehouse', 'length', 'max' => 4),
            array('ptype', 'length', 'max' => 1),
            array('jbclass', 'length', 'max' => 40),
            array('serial', 'length', 'max' => 30),
            array('eqcounter', 'length', 'max' => 8),
            array('entryid, assemblyid', 'length', 'max' => 36),
            array('partno', 'exist', 'className' => 'Inventory', 'attributeName' => 'partno', 'allowEmpty' => true),
            array('warranty', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, invoice, counter, partno, firstline, description, qty, price, warehouse, ptype, jbclass, serial, sdebit, scredit, cost, cdebit, ccredit, tax1, tax2, tax3, tax4, tax5, tax6, epa, miscnum, warranty, refrlbs, noprint, taxed, costed, eqcounter, entryid, assemblyid, assemblyqty, markupvalue', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'invoiceModel' => array(self::BELONGS_TO, 'Invoice', 'invoice'),
            'inventory' => array(self::BELONGS_TO, 'Inventory', 'partno'),
        );
    }

    public function getInvoiceType() {
        $type = Yii::app()->db->createCommand('select invoicetype from tbl_invoice where invoice=:invoice')
                        ->bindValue('invoice', $this->invoice)->queryScalar();
        return $type;
    }

    public function getTax() {
        $tax = Taxcode::model()->find('code=:taxcode', array(
            'taxcode' => $this->invoiceModel->taxcode
        ));
        return $tax;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'invoice' => 'Invoice',
            'counter' => 'Counter',
            'partno' => 'Partno',
            'firstline' => 'Firstline',
            'description' => 'Description',
            'qty' => 'Qty',
            'price' => 'Price',
            'warehouse' => 'Warehouse',
            'ptype' => 'Ptype',
            'jbclass' => 'Jbclass',
            'serial' => 'Serial',
            'sdebit' => 'Sdebit',
            'scredit' => 'Scredit',
            'cost' => 'Cost',
            'cdebit' => 'Cdebit',
            'ccredit' => 'Ccredit',
            'tax1' => 'Tax1',
            'tax2' => 'Tax2',
            'tax3' => 'Tax3',
            'tax4' => 'Tax4',
            'tax5' => 'Tax5',
            'tax6' => 'Tax6',
            'epa' => 'Epa',
            'miscnum' => 'Miscnum',
            'warranty' => 'Warranty',
            'refrlbs' => 'Refrlbs',
            'noprint' => 'Noprint',
            'taxed' => 'Taxed',
            'costed' => 'Costed',
            'eqcounter' => 'Eqcounter',
            'entryid' => 'Entryid',
            'assemblyid' => 'Assemblyid',
            'assemblyqty' => 'Assemblyqty',
            'markupvalue' => 'Markupvalue',
        );
    }

    public function getYesNoList() {
        return array(
            '0' => 'Yes',
            '1' => 'No'
        );
    }

    public function getYesNoValue($value) {
        return isset($this->yesNoList[$value]) ? $this->yesNoList[$value] : NULL;
    }

    
    public function afterDelete() {
        DelInvoiceLedger::copyFromInvoiceLedgerAndSave($this);
        return parent::afterDelete();
    }

    public function beforeSave() {
        if ($this->partno != NULL) {

            if ($this->inventory != NULL) {
                if ($this->description == NULL) {
                    $this->description = $this->inventory->description;
                }
                if ($this->price == NULL) {
                    $this->price = $this->inventory->getPrice($this->invoiceModel->pricecode);
                }

                $subcat = $this->inventory->getSubcategory();
                if ($subcat != NULL) {
                    if ($subcat->applymarkup == 'Average Cost')
                        $this->cost = $this->inventory->averagecost;
                    else
                        $this->cost = $this->inventory->baseprice;
                }

                $this->scredit = $this->inventory->salescredit;
                $this->sdebit = $this->inventory->salesdebit;
                $this->cdebit = $this->inventory->costcredit;
                $this->ccredit = $this->inventory->costdebit;
            }
        }
        if ($this->isNewRecord) {

            $max = Yii::app()->db->createCommand('select max(cast(counter as unsigned)) from tbl_invoice_ledger where invoice=:invoice')->bindValue('invoice', $this->invoice)->queryScalar();
            $this->counter = str_pad($max + 1, 3, '0', STR_PAD_LEFT);
        }
        $this->adjustQTY();
        //write material tax
        $this->tax1 = $this->getItemTax();
        return parent::beforeSave();
    }
public function beforeDelete() {
         switch ($this->partno) {
            case 'MISC':
            case 'HIST':
            case 'hist':
            case 'FUEL':
            case 'ATM-LAB':  
                return parent::beforeDelete();
        }
            if($this->getInvoiceType() != Invoice::TYPE_INVOICE || $this->getInvoiceType() != Invoice::TYPE_INVOICE)
          return parent::beforeDelete();
            $invActModel = new Inventoryact();
            $invActModel->attributes = $this->attributes;
            $invActModel->partdesc = $this->description;
            $invActModel->description = 'Adjustment';

            $invActModel->qty = $this->qty;


            $invActModel->source = 'A';

            if ($this->getInvoiceType() == Invoice::TYPE_CREDIT_MEMO) {
                $invActModel->cost = -1;
                $invActModel->rdate = DateUtil::getDefaultCurrentDateTime();
                $invActModel->rtime = DateUtil::getDefaultCurrentTime();
                $invActModel->type = 'O';
                $invActModel->reason = 'Removed from credit memo no:' . $this->invoice;
                $this->removeInvAct($invActModel->qty);
            }
            if ($this->getInvoiceType() == Invoice::TYPE_INVOICE) {
                $invActModel->type = 'I';
                $invActModel->reason = 'Removed from invoice no:' . $this->invoice;
              
            }

            $invActModel->save();
        return parent::beforeDelete();
    }

    protected function adjustQTY() {
           
        switch ($this->partno) {
            case 'MISC':
            case 'HIST':
            case 'hist':
            case 'FUEL':
            case 'ATM-LAB': return;
        }
        
  
        if($this->getInvoiceType() != Invoice::TYPE_INVOICE && $this->getInvoiceType() != Invoice::TYPE_CREDIT_MEMO)
            return;
    
        if ($this->isNewRecord) {
      
            $invActModel = new Inventoryact();
            $invActModel->attributes = $this->attributes;
            $invActModel->partdesc = $this->description;
            $invActModel->description = 'Adjustment';

            $invActModel->qty = $this->qty;


            $invActModel->source = 'A';

            if ($this->getInvoiceType() == Invoice::TYPE_INVOICE) {
                $invActModel->cost = -1;
                $invActModel->rdate = DateUtil::getDefaultCurrentDateTime();
                $invActModel->rtime = DateUtil::getDefaultCurrentTime();
                $invActModel->type = 'O';
                $invActModel->reason = 'Added to invoice no:' . $this->invoice;
                $this->removeInvAct($invActModel->qty);
            }
            if ($this->getInvoiceType() == Invoice::TYPE_CREDIT_MEMO) {
           
                $invActModel->type = 'I';
                $invActModel->reason = 'Added to credit memo no:' . $this->invoice;
               
            }

            $invActModel->save();
        } else {
               
            if ($this->qty != $this->old_qty) {
                $diff = $this->qty - $this->old_qty;
                $invActModel = new Inventoryact();
                $invActModel->attributes = $this->attributes;
                $invActModel->partdesc = $this->description;
                $invActModel->description = 'Adjustment';



                $invActModel->source = 'A';
                echo $diff;
                if ($this->getInvoiceType() == Invoice::TYPE_INVOICE) {
                    if ($diff > 0) {
                        $invActModel->rdate = DateUtil::getDefaultCurrentDateTime();
                        $invActModel->rtime = DateUtil::getDefaultCurrentTime();
                        $invActModel->cost = -1;
                        $invActModel->qty = $diff;
                        $invActModel->type = 'O';
                        $invActModel->reason = 'INV:' . $this->invoice;
                          $this->removeInvAct($invActModel->qty);
                        
                    } else {
                        $invActModel->cost = 1;
                        $invActModel->qty = -$diff;
                        $invActModel->type = 'I';
                          $invActModel->reason = 'INV:' . $this->invoice;
                    }
                }
                if ($this->getInvoiceType() == Invoice::TYPE_CREDIT_MEMO) {
                    echo 'CM logic';
                       if ($diff < 0) {
                        $invActModel->rdate = DateUtil::getDefaultCurrentDateTime();
                        $invActModel->rtime = DateUtil::getDefaultCurrentTime();
                        $invActModel->cost = -1;
                        $invActModel->qty = -$diff;
                        $invActModel->type = 'O';
                        $invActModel->reason = 'CM:' . $this->invoice;
                        $this->removeInvAct($invActModel->qty);
                        } else {
                        $invActModel->cost = 1;
                        $invActModel->qty = $diff;
                        $invActModel->type = 'I';
                        $invActModel->reason = 'CM:' . $this->invoice;
                    }
                }
                echo $invActModel->qty;
                $invActModel->validate();
                print_r($invActModel->getErrors());
                var_dump($invActModel->save());
            }
        }
    }
    protected function removeInvAct($removeAmount){
        $criteria = new CDbCriteria();
        $criteria->condition = "partno ='$this->partno' and type='I' and warehouse='$this->warehouse'";
        $criteria->order = "id ASC";
        $inModels = Inventoryact::model()->findAll($criteria);
               foreach ($inModels as $inModel) {
            if ($removeAmount) {
                /** @var $inModel Inventoryact */

                $diff = $inModel->qty - $inModel->qtyout ;

                If ($diff >=$removeAmount) {
                    $inModel->qtyout += $removeAmount;
                            $removeAmount =0;
                } else {
                    $inModel->qtyout +=$diff;
                    $removeAmount -= $diff;
                    $inModel->type ='X';
                }
                $inModel->cost = 1;
                 $inModel->source ='A';
                $inModel->description = 'Adjustment';
                $inModel->save();
            }
            if($inModel->qty == $inModel->qtyout){
                $inModel->type ='X';
                $inModel->save();
            }
        }
    }

    public function autoSetTaxed($custno) {
        if ($this->inventory != NULL) {
            if ($this->inventory->isTaxable($custno)) {
                $this->taxed = self::TAXED;
            } else {
                $this->taxed = self::NO_TAXED;
            }
        }
    }

    public function getItemSubTotal() {
        return $this->price * $this->qty;
    }

    public function getCustno() {
        $custno = Yii::app()->db->createCommand('select custno from tbl_invoice where invoice=:invoice')
                        ->bindValues(array('invoice' => $this->invoice))->queryScalar();
        return $custno;
    }

    public function getItemTotal() {
        return $this->getItemSubTotal() * $this->getItemTax();
    }

    public function getItemTax($taxModel = null) {
        $taxModel = $taxModel != null ? $taxModel : $this->invoiceModel->getTaxModel();
        /* @var $tax Taxcode */
        if ($taxModel != NULL) {
            if ($this->taxed == 0) {
                return $this->getItemSubTotal() * $taxModel->salestaxrate / 100;
            }
        }

        return 0;
    }

}

